package net.lulihu.common_util.validated.spring;

import net.lulihu.ObjectKit.CollectionKit;

import javax.validation.ConstraintViolationException;
import javax.validation.Path;
import java.util.ArrayList;
import java.util.List;

/**
 * 参数约束违规例外工具
 */
public class ParamViolationExceptionUtil {


    /**
     * 获取参数违规消息
     *
     * @param violation 违规异常
     * @return 消息
     */
    public static List<String> getParamViolationMessages(ConstraintViolationException violation) {
        return CollectionKit.listToList(violation.getConstraintViolations(),
                (v) -> {
                    StringBuilder str = new StringBuilder();
                    List<String> nodeName = new ArrayList<>();
                    for (Path.Node node : v.getPropertyPath()) {
                        nodeName.add(node.getName());
                    }
                    int size = nodeName.size();
                    int start = size == 2 ? 1 : (size > 2 ? 2 : 0);

                    String paramName = CollectionKit.join(CollectionKit.sub(nodeName, start, size), ".");
                    return str.append(paramName).append(":").append(v.getMessage()).toString();
                });
    }

}
